package product;

import java.util.HashSet;
import java.util.Set;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class counthali {

	/**统计山东省售卖蛤蜊的农产品市场占全省农产品市场的比例
	 * @param args
	 */
	public static void main(String[] args)throws Exception {

		if(args.length!=2){
			System.err.println("user path err!!");
			System.exit(-1);
		}
		@SuppressWarnings("deprecation")
		Job job=new Job(new Configuration(), "count");
		job.setJarByClass(counthali.class);
		
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job,new Path(args[1]));
		
		job.setMapperClass(cMaps.class);
		job.setReducerClass(cReduces.class);
		
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(IntWritable.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(DoubleWritable.class);
		job.waitForCompletion(true);
	}
	public static class cMaps extends Mapper<LongWritable,Text,Text,IntWritable>{
		protected void map(LongWritable key, Text value, org.apache.hadoop.mapreduce.Mapper<LongWritable,Text,Text,IntWritable>.Context context) throws java.io.IOException ,InterruptedException {
			String[] lines = value.toString().split("\t");
			int count=0;
			if (lines.length==6 && lines[4].equals("山东")) {	
				count++;
			}
			context.write(new Text(lines[0]), new IntWritable(count));
		};
	}
	public static class cReduces extends Reducer<Text,IntWritable,Text,DoubleWritable>{
		Set<String> set1 = new HashSet<String>();
		Set<String> set2 = new HashSet<String>();
		
		protected void reduce(Text k2, java.lang.Iterable<IntWritable> values, org.apache.hadoop.mapreduce.Reducer<Text,IntWritable,Text,DoubleWritable>.Context context) throws java.io.IOException ,InterruptedException {
		for (IntWritable cnt : values) {
			if(k2.toString().contains("蛤蜊")){
				set1.add(k2.toString());
			}
			set2.add(k2.toString());
		}	
		};
		protected void cleanup(org.apache.hadoop.mapreduce.Reducer<Text,IntWritable,Text,DoubleWritable>.Context context) throws java.io.IOException ,InterruptedException {
			double a=set1.size();
			double b=set2.size();
			double c=a/b;
			context.write(new Text("山东省售卖蛤蜊的农产品市场占全省农产品市场的比例:"),new DoubleWritable(c));
		};
	}

}
